
import React from 'react'
import ReactDOM from 'react-dom'

import * as SubscribeMessageAction  from '../actions/SubscribeMessageAction';
import { connect }  from 'react-redux';

import MenuSettingAssetSelect from './MenuSettingAssetSelect'
import AssetGridCell from './AssetGridCell'

class MessSettingBtn extends React.Component{
  constructor(props){
    super(props)
  }
  render (){
    return(
      <div className = "Settingbutton">
        <button type="button" className="btn btn-create saveBtn" onClick={(event)=>this.props.onSubmitClick(event)} >保存</button>
      </div>
    )
  }
}

class FollowMessageTable extends React.Component {
  constructor(props) {
    super(props)

    this.state = {

    }
  }

  componentDidMount(){

  }

  componentWillReceiveProps(props) {
    this.setState({
      data: props.data,
      type: props.data?props.data.responseType : ''
    })
  }

  selectTextTab(){
    // console.log('text')
    var data = this.state.data;
    if (data) {
      data.responseType = 'text';
    }
    this.setState({
      type: 'text',
      data: data
    })
  }

  selectPicTab(){
    // console.log('news')
    var data = this.state.data;
    if (data) {
      data.responseType = 'news';
    }
    this.setState({
      type: 'news',
      data: data
    })
  }

  onTextChange(event) {
    var value = $(event.target).val();
    var data = this.state.data;
    var content = {
      text: value
    }
    if (data) {
      data.content = content;
      data.responseType = 'text';
    }else {
      data = {
        content: content,
        responseType: 'text'
      }
    }
    this.setState({
      data: data
    })
    this.props.onTextChange(data)
  }

  renderEditView() {
    var self = this;
    if (this.state.type == 'news') {
      if (!this.state.data) {
        return (
          <tr>
            <td>

              <div>
                <button type="button" className="btn btn-create saveBtn" onClick={(event)=>this.props.onAssetGridShow(event)} >选择图文</button>
              </div>
              <div className="edit" >
              </div>
            </td>
          </tr>
        )
      }else {

        var content = this.state.data.content
        if (!content.news) {
          return (
            <tr>
              <td>

                <div>
                  <button type="button" className="btn btn-create saveBtn" onClick={(event)=>this.props.onAssetGridShow(event)} >选择图文</button>
                </div>
                <div className="edit" >
                </div>
              </td>
            </tr>
          )
        }
        var news_item = []
        for (var i = 0; i < content.news.length; i++) {
          var news = content.news[i];
          news_item.push({
            digest: news.msgDescription,
            url: news.msgUrl,
            title: news.msgTitle,
            thumb_url: news.msgPicUrl,
            thumb_media_id: news.msgPicId
          })
        }
        var assetContent = {
          content:{
            news_item: news_item
          }
        }
        return (
          <tr>
            <td>

              <div className="col-sm-6">
                <button type="button" className="btn btn-create saveBtn" onClick={(event)=>this.props.onAssetGridShow(event)} >选择图文</button>
              </div>
              <div className="edit asset-grid" >
                <AssetGridCell
                  wechat = {self.props.wechat}
                  data = {assetContent}/>
              </div>
            </td>
          </tr>
        )
      }

    }else {
      var text = "";
      if (this.state.data) {
        var content = this.state.data.content
        text = this.state.data.content.text;
      }
      return (
        <tr>
          <td>
            <div className="edit" >
              <textarea className="editTextarea" maxLength="600" onChange={(event)=>this.onTextChange(event)} value={text}></textarea>
            </div>
          </td>
        </tr>
      )
    }
  }

  render () {

    return(
      <div className="ReplyEditTable">
        <table className="table table-bordered">
          <thead>
                <a data-toggle="tooltip" data-placement="top" onClick={(event)=>this.selectPicTab(event)}>
                  <span className="glyphicon glyphicon-picture photoLabel"> 图文</span>
                </a>
                <a data-toggle="tooltip" data-placement="top" onClick={(event)=>this.selectTextTab(event)}>
                  <span className="glyphicon glyphicon-pencil textLabel"> 文本</span>
                </a>
          </thead>
          <tbody>
            {this.renderEditView()}
          </tbody>

      </table>
      <MessSettingBtn
        onSubmitClick = {this.props.onSubmitClick.bind(this)}
        />
    </div>
    )
  }
}

class MessageSettingEventsRec extends React.Component {
  constructor(props) {
    super(props)
    this.state = {

    }
  }

  componentDidMount(){
    var self = this;
    var appId = self.props.wechat.length > 0?self.props.wechat[0].appId:''
    this.props.dispatch(
      SubscribeMessageAction.loadMessageHandlerAsync({
        appId: appId
      })
    )
    this.$assetModal = $(ReactDOM.findDOMNode(this.refs.MessageSettingPictureEdit))

  }

  componentDidUpdate() {
    // console.log(this.props.data)
  }

  componentWillReceiveProps(props) {
    this.setState({
      data: props.data
    })
  }

  onAssetGridShow() {
    this.$assetModal.modal("show")
  }

  onAssetGridClick(media_id, data) {

    var items = data.news_item;
    var news = [];
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      news.push({
        msgUrl: item.url,
        msgTitle: item.title,
        msgPicUrl: item.thumb_url,
        msgPicId: item.thumb_media_id,
        msgDescription: item.digest
      })
    }
    var content = {
      news: news
    }
    var newData = this.state.data;
    newData = {
      content: content,
      responseType: 'news'
    };

    this.setState({
      data: newData
    })
    this.$assetModal.modal("hide")
  }

  onTextChange(data) {
    this.setState({
      data: data
    })
  }

  onSubmitClick() {
    var self = this;
    var appId = self.props.wechat.length > 0?self.props.wechat[0].appId:''
    var data = this.state.data
    if (data.responseType == 'text' && (!data.content.text || data.content.text.trim().length==0)) {
      alert("请输入文字!")
      return;
    }else if (data.responseTyp == 'news' && (!data.content.news || data.content.news.length==0)){
      alert("请选择图文!")
      return;
    }

    var requestData = {
      appId: appId,
      responseType: data.responseType,
      content: data.content
    }

    this.props.dispatch(
      SubscribeMessageAction.createMessageHandlerAsync(requestData)
    )
  }

  render (){
    var self = this;
    return(
      <div className="message-follow-content">
        <FollowMessageTable
          onTextChange = {this.onTextChange.bind(self)}
          onAssetGridShow = {this.onAssetGridShow.bind(self)}
          onSubmitClick = {this.onSubmitClick.bind(self)}
          data = {this.state.data}
          wechat = {this.props.wechat}
        />
        <MenuSettingAssetSelect
          ref = "MessageSettingPictureEdit"
          wechat = {this.props.wechat}
          onAssetGridClick = {this.onAssetGridClick.bind(self)}
          />

      </div>
    )
  }
}


const mapStateToProps = (state, ownProps) => {
  return { data: state.subscribeMessage }
}

export default connect(mapStateToProps)(MessageSettingEventsRec)
